package com.easpeed.elevator.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.bigyu.utils.Logger;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.util.Consumer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.easpeed.common.CommonConsts;
import com.easpeed.comon.bean.BaseData;
import com.easpeed.comon.bean.LoginResult;
import com.easpeed.comon.consts.ConstsOpticalData;
import com.easpeed.comon.utils.Line;
import com.easpeed.comon.utils.NetHelper;
import com.easpeed.elevator.R;
import com.easpeed.elevator.base.BaseActivity;
import com.easpeed.elevator.bean.LineBean;
import com.easpeed.elevator.bean.OpticalBean;
import com.easpeed.elevator.event.SendOrderEvent;
import com.easpeed.elevator.utils.CallbackInterface;
import com.easpeed.elevator.utils.NoticeDialog;
import com.easpeed.elevator.utils.WwAdapter;
import com.easpeed.elevator.utils.WwViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import butterknife.ButterKnife;


public class LineManageActivity extends BaseActivity {


    private ArrayList<LineBean> lineList = new ArrayList<>();
    private ArrayList<OpticalBean> opticalList = new ArrayList<>();

    String str = "";
    WwViewHolder holder;

    private NetHelper netHelper;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, LineManageActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void getIntentData(Bundle savedInstanceState) {

    }

    @Override
    protected void loadXml() {
        setContentView(R.layout.activity_linemanage);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        holder = new WwViewHolder(this, this.getWindow().getDecorView());
        netHelper = new NetHelper(this);
    }

    @Override
    protected void initView() {
        initLineView(holder.getView(R.id.layout_line));
        initOpticalView(holder.getView(R.id.layout_optical));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    @Override
    protected void initData() {
        readData();
        currentLine = lineList.isEmpty() ? null : lineList.get(0);
        if (currentLine != null && currentLine.getOpticalList() != null) {
            opticalList.clear();
            opticalList.addAll(currentLine.getOpticalList());
        }
        wwAdapter.notifyDataSetChanged();
        wwAdapterOptical.notifyDataSetChanged();

        renderBaseView();

    }

    private void renderBaseView() {
        holder.setVisible(R.id.item_manager_root_1, lineList.isEmpty());
        holder.setVisible(R.id.item_manager_root_2, !lineList.isEmpty());

    }


    @Override
    protected void registerListener() {
        holder.setOnClickListener(R.id.back, view -> finish());
        holder.setOnClickListener(R.id.create_line, view -> {
            //创建线路
            createLine("", "新增线路", message -> createLine(message));
        });
        holder.setOnClickListener(R.id.create_optical_2, view -> {
            //创建线路
            createOptical("新增光缆", null, data -> createOptical(data));
        });
        holder.setOnClickListener(R.id.create_optical_1, view -> {
            //创建线路
            createOptical("新增光缆", null, data -> createOptical(data));
        });
        holder.setOnClickListener(R.id.create_line_2, view -> {
            //创建线路
            createLine("", "新增线路", message -> createLine(message));
        });
    }

    private void createOptical(OpticalBean data) {
        if (data == null) {
            ToastUtils.showShort("创建光缆失败");
        } else {
            if (currentLine == null) {
                return;
            }
            if (currentLine.getOpticalList() == null) {
                currentLine.setOpticalList(new ArrayList<>());
            }
            currentLine.getOpticalList().add(data);
            opticalList.clear();
            opticalList.addAll(currentLine.getOpticalList());
            wwAdapter.notifyDataSetChanged();
            wwAdapterOptical.notifyDataSetChanged();
            ToastUtils.showShort("创建光缆成功");
        }
    }

    /**
     * 创建线路
     *
     * @param message
     */
    private void createLine(String message) {
        if (TextUtils.isEmpty(message)) {
            ToastUtils.showShort("创建线路失败");
        } else {

            HashMap<String, Object> map = new HashMap<>();
            map.put("lineName", message);
            map.put("deviceCode", CommonConsts.getTargetDeviceId());
            netHelper.netForCreateLine(true, map, new Consumer<BaseData<Line>>() {
                @Override
                public void accept(BaseData<Line> loginResultBaseData) {

                }
            });


            for (LineBean bean : lineList) {
                if (message.equals(bean.getLineName())) {
                    ToastUtils.showShort("创建线路失败,线路名称重复");
                    return;
                }
            }
            LineBean bean = new LineBean(message, UUID.randomUUID().toString());
            lineList.add(0, bean);
            if (lineList.size() == 1) {
                currentLine = bean;
            }
            renderBaseView();
            wwAdapter.notifyDataSetChanged();
            wwAdapterOptical.notifyDataSetChanged();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        saveData();
    }


    @Subscribe
    public void onEventMainThread(SendOrderEvent event) {

    }

    private void readData() {
        lineList.clear();
        try {
            String path = getFilesDir().getAbsolutePath();
            File file = new File(path + File.separator + "line.json");
            File fileTemp = new File(path + File.separator + "line_temp.json");
            if (file.exists()) {
                if (fileTemp.exists()) {
                    fileTemp.delete();
                }
                boolean copySuccess = FileUtils.copyFile(file, fileTemp);
                Logger.e("TAG", "备份文件成功：" + copySuccess);
            }
            boolean success = FileUtils.createOrExistsFile(file);
//            success = FileUtils.writeFileFromString(file, "111111", false);
            String file2String = FileUtils.readFile2String(file, "utf-8");
            Logger.e("TAG", "initData: " + file2String);

            Gson gson = new Gson();
            Type type = new TypeToken<List<LineBean>>() {
            }.getType();
            List<LineBean> list = (List<LineBean>) gson.fromJson(file2String, type);
            lineList.addAll(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveData() {

        try {
            Gson gson = new Gson();
            String json = gson.toJson(lineList);
            String path = getFilesDir().getAbsolutePath();
            File file = new File(path + File.separator + "line.json");
            File fileTemp = new File(path + File.separator + "line_temp.json");
            if (file.exists()) {
                if (fileTemp.exists()) {
                    fileTemp.delete();
                }
                boolean copySuccess = FileUtils.copyFile(file, fileTemp);
                Logger.e("TAG", "备份文件成功：" + copySuccess);
            }
            FileUtils.writeFileFromString(file, json, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建线路
     */
    private void createLine(String defaultTxt, String title, CallbackInterface<String> callbackInterface) {
        NoticeDialog dialog = new NoticeDialog.Builder(holder.mContext).setLayoutId(R.layout.dialog_create_line).setClickBtnDismissDialog(true).setCanCancel(true).setCanceledOnTouchOutside(true).create();
        dialog.setOnclickListener(R.id.close, v -> {
            dialog.dismiss();
        });
        dialog.setText(R.id.input, defaultTxt);
        dialog.setText(R.id.title, title);
        dialog.setOnclickListener(R.id.sure, v -> {
            String input = ((TextView) dialog.getView(R.id.input)).getText().toString();
            callbackInterface.onCallback(input);
        });

        dialog.setGravity(Gravity.CENTER);
        dialog.show();
    }


    private LineBean currentLine;

    private String opticalUuid;

    private WwAdapter<LineBean> wwAdapter;
    private WwAdapter<OpticalBean> wwAdapterOptical;

    private void initLineView(RecyclerView recyclerView) {
        wwAdapter = new WwAdapter<LineBean>() {

            @Override
            public void initRecyclerView(Context mContext, WwAdapter<LineBean> adapter) {
                LinearLayoutManager manager = new LinearLayoutManager(holder.mContext, LinearLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(manager);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public int getLayoutId() {
                return R.layout.item_line_info;
            }

            @Override
            public void convert(WwViewHolder holder, LineBean bean, int position) {
                holder.setText(R.id.tv_line_name, bean.getLineName());

                holder.setActivated(R.id.left_line, currentLine == bean);
                holder.setActivated(R.id.root, currentLine == bean);
                holder.setActivated(R.id.detail, currentLine == bean);
                if (currentLine == bean) {
                    renderOpticalLine(bean.getOpticalList());
                }

                holder.setOnClickListener(R.id.edit, view -> {
                    createLine(bean.getLineName(), "编辑线路", message -> {
                        if (TextUtils.isEmpty(message)) {
                            ToastUtils.showShort("编辑线路失败");
                        } else {
                            for (LineBean tempBean : lineList) {
                                if (message.equals(tempBean.getLineName())) {
                                    ToastUtils.showShort("编辑线路名称失败,线路名称重复");
                                    return;
                                }
                            }
                            bean.setLineName(message);
                            wwAdapter.notifyDataSetChanged();
                        }
                    });
                });
                //选择线路
                holder.setOnClickListener(R.id.root, view -> {
                    currentLine = bean;
                    opticalList.clear();
                    if (bean.getOpticalList() != null) {
                        opticalList.addAll(bean.getOpticalList());
                        wwAdapterOptical.notifyDataSetChanged();
                    }
                    wwAdapter.notifyDataSetChanged();
                });
                //删除线路
                holder.setOnClickListener(R.id.delete, view -> {
                    lineList.remove(bean);
                    if (currentLine == bean) {
                        if (lineList.isEmpty()) {
                            currentLine = null;
                        } else {
                            currentLine = lineList.get(0);
                            opticalList.clear();
                            if (currentLine == null) {
                                return;
                            }
                            if (currentLine.getOpticalList() != null) {
                                opticalList.addAll(currentLine.getOpticalList());
                                wwAdapterOptical.notifyDataSetChanged();
                            }

                        }
                    }
                    wwAdapter.notifyDataSetChanged();
                    renderBaseView();
                });
            }
        }.create(holder.mContext, lineList);
    }

    private void initOpticalView(RecyclerView recyclerView) {
        wwAdapterOptical = new WwAdapter<OpticalBean>() {

            @Override
            public void initRecyclerView(Context mContext, WwAdapter<OpticalBean> adapter) {
                LinearLayoutManager manager = new LinearLayoutManager(holder.mContext, LinearLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(manager);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public int getLayoutId() {
                return R.layout.item_optical_info;
            }

            @Override
            public void convert(WwViewHolder holder, OpticalBean bean, int position) {
                holder.setText(R.id.tv_line_name, bean.getName());
                holder.setText(R.id.level, bean.getLevel());
                holder.setText(R.id.zjd, bean.getZjd());
                holder.setText(R.id.count, bean.getNumber());
                holder.setText(R.id.number, bean.getCodeMark());
                holder.setText(R.id.length, bean.getLength());
                holder.setText(R.id.remark, bean.getRemark());

                holder.setVisible(R.id.layout_optical_info, Objects.equals(opticalUuid, bean.getId()));
                holder.setActivated(R.id.detail, Objects.equals(opticalUuid, bean.getId()));

                holder.setOnClickListener(R.id.root, view -> {
                    if (Objects.equals(opticalUuid, bean.getId())) {
                        opticalUuid = null;
                    } else {
                        opticalUuid = bean.getId();
                    }
                    wwAdapterOptical.notifyDataSetChanged();
                    wwAdapter.notifyDataSetChanged();
                });

                holder.setOnClickListener(R.id.edit, view -> {
                    createOptical("编辑光缆", bean, new CallbackInterface<OpticalBean>() {
                        @Override
                        public void onCallback(OpticalBean data) {
                            wwAdapterOptical.notifyDataSetChanged();
                            wwAdapter.notifyDataSetChanged();
                        }
                    });
                });

                holder.setOnClickListener(R.id.delete, view -> {
                    if (currentLine == null) {
                        return;
                    }
                    if (currentLine.getOpticalList() != null) {
                        currentLine.getOpticalList().remove(bean);
                        opticalList.remove(bean);
                    }
                    wwAdapterOptical.notifyDataSetChanged();
                    wwAdapter.notifyDataSetChanged();

                });

            }
        }.create(holder.mContext, opticalList);
    }

    private void renderOpticalLine(@Nullable List<OpticalBean> opticalBeanList) {
        if (opticalBeanList == null || opticalBeanList.isEmpty()) {
            holder.setVisible(R.id.layout_empty_optical, true);
            holder.setVisible(R.id.layout_optical_list, false);
        } else {
            holder.setVisible(R.id.layout_optical_list, true);
            holder.setVisible(R.id.layout_empty_optical, false);
        }

    }


    /**
     * 创建光缆
     */
    private void createOptical(String defaultTxt, OpticalBean bean, CallbackInterface<OpticalBean> callbackInterface) {
        NoticeDialog dialog = new NoticeDialog.Builder(holder.mContext).setLayoutId(R.layout.dialog_create_optical).setClickBtnDismissDialog(false).setCanCancel(true).setCanceledOnTouchOutside(true).create();
        dialog.setDialogWith(0, 0);
        dialog.setGravity(Gravity.CENTER);
        dialog.setOnclickListener(R.id.close, v -> {
            dialog.dismiss();
        });
        if (bean != null) {
            dialog.setText(R.id.name, bean.getName());
            dialog.setText(R.id.level, bean.getLevel());
            dialog.setText(R.id.zjd, bean.getZjd());
            dialog.setText(R.id.count, bean.getNumber());
            dialog.setText(R.id.number, bean.getCodeMark());
            dialog.setText(R.id.length, bean.getLength());
            dialog.setText(R.id.remark, bean.getRemark());
        }
        dialog.setText(R.id.title, defaultTxt);

        AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) dialog.getView(R.id.level);
        // 准备下拉选项数据
        ArrayAdapter<String> adapter = new ArrayAdapter<>(holder.mContext, android.R.layout.simple_dropdown_item_1line, ConstsOpticalData.options);
        autoCompleteTextView.setAdapter(adapter);
        autoCompleteTextView.setOnClickListener(v -> autoCompleteTextView.showDropDown());


        dialog.setOnclickListener(R.id.reduce, v -> {
            String count = dialog.getText(R.id.count);
            if (count != null && !count.isEmpty()) {
                int result = Integer.parseInt(count) - 1;
                dialog.setText(R.id.count, result + "");
            }

        });
        dialog.setOnclickListener(R.id.add, v -> {
            String count = dialog.getText(R.id.count);
            if (count != null && !count.isEmpty()) {
                int result = Integer.parseInt(count) + 1;
                dialog.setText(R.id.count, result + "");
            }
        });

        dialog.setOnclickListener(R.id.sure, v -> {
            for (OpticalBean opticalBean : opticalList) {
                if (bean != null && TextUtils.equals(bean.getId(), opticalBean.getId())) {
                    continue;
                }
                if (TextUtils.equals(opticalBean.getName(), dialog.getText(R.id.name))) {

                    ToastUtils.showShort("光缆不可名称重复");
                    return;
                }
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.name))) {
                ToastUtils.showShort("请输入光缆名称");
                return;
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.level))) {
                ToastUtils.showShort("请选择光缆级别");
                return;
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.zjd))) {
                ToastUtils.showShort("请输入中继段");
                return;
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.count))) {
                ToastUtils.showShort("请输入纤芯数量");
                return;
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.number))) {
                ToastUtils.showShort("请输入纤芯编号");
                return;
            }
            if (dialog.getText(R.id.number).split("；").length > Integer.parseInt(dialog.getText(R.id.count))) {
                ToastUtils.showShort("纤芯数量应大于等于纤芯编号数量");
                return;
            }

            if (TextUtils.isEmpty(dialog.getText(R.id.length))) {
                ToastUtils.showShort("请输入纤芯长度");
                return;
            }


            OpticalBean opticalBean = new OpticalBean(UUID.randomUUID().toString());
            if (bean != null) {
                opticalBean = bean;
            }
            opticalBean.setName(dialog.getText(R.id.name));
            opticalBean.setLevel(dialog.getText(R.id.level));
            opticalBean.setZjd(dialog.getText(R.id.zjd));
            opticalBean.setNumber(dialog.getText(R.id.count));
            opticalBean.setCodeMark(dialog.getText(R.id.number));
            opticalBean.setLength(dialog.getText(R.id.length));
            opticalBean.setRemark(dialog.getText(R.id.remark));
            callbackInterface.onCallback(opticalBean);
            dialog.dismiss();
        });

        dialog.setGravity(Gravity.CENTER);
        dialog.show();
    }
}
